package com.luo.d3s.light.jpa.ec.infrastructure.database.specification;

import com.luo.d3s.light.jpa.ec.application.dto.query.OrderPageQuery;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.*;
import java.util.List;
import java.util.Objects;

/**
 * 订单分页列表查询条件（Spring Data JPA）
 *
 * @author luohq
 * @date 2023-07-30
 */
public class OrderPageQuerySpecification implements Specification {

    private OrderPageQuery orderPageQuery;

    public OrderPageQuerySpecification(OrderPageQuery orderPageQuery) {
        this.orderPageQuery = orderPageQuery;
    }

    @Override
    public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {

        Predicate conjunctionPredicate = cb.conjunction();
        List<Expression<Boolean>> expressions = conjunctionPredicate.getExpressions();
        //create_time >= :createTimeStart and create_time <= :createTimeEnd
        if (Objects.nonNull(this.orderPageQuery.getCreateTimeStart())) {
            expressions.add(cb.greaterThanOrEqualTo(root.get("createTime"), this.orderPageQuery.getCreateTimeStart()));
        }
        if (Objects.nonNull(this.orderPageQuery.getCreateTimeEnd())) {
            expressions.add(cb.lessThanOrEqualTo(root.get("createTime"), this.orderPageQuery.getCreateTimeEnd()));
        }
        return conjunctionPredicate;
    }
}
